package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.constant.MessageConstant;
import com.atguigu.entity.Result;
import com.atguigu.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {

    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    //findById
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map result=orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,result);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }

    }


    @RequestMapping("/save")
    public Result saveOrder(@RequestBody Map map){
        Jedis jedis = jedisPool.getResource();
        try {
            String requestCode=(String) map.get("validateCode");
            String telephone = map.get("telephone").toString();
            String redisCode = jedis.get(telephone);
            if(redisCode == null  || !redisCode.equals(requestCode)){
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            int orderId=orderService.save(map);
           return new Result(true,MessageConstant.ORDER_SUCCESS,orderId);
        } catch (Exception e) {
            return new Result(false,e.getMessage());
        } finally {
            jedis.close();
        }
    }
}
